const express = require('express');
const router = express.Router();
const { User } = require('../models');

// 根路径路由
router.get('/', (req, res) => {
  res.send('Welcome to Flower Workshop API');
});

// 获取所有用户
router.get('/users', async (req, res) => {
  try {
    const users = await User.findAll({
      limit: 10,
      order: [['id', 'ASC']]
    });
    
    res.json({ 
      ok: true, 
      data: users.map(user => user.toJSON()),
      metadata: {
        count: users.length,
        timestamp: new Date().toISOString(),
        author: require('../package.json').author,
        version: require('../package.json').version
      }
    });
  } catch (err) {
    console.error('获取用户列表错误:', err);
    res.status(500).json({ 
      ok: false, 
      error: err.message,
      detail: '请检查数据库连接和表结构'
    });
  }
});

// 根据ID查询用户
router.get('/users/:id', async (req, res) => {
  try {
    const user = await User.findByPk(req.params.id);
    if (!user) {
      return res.status(404).json({ 
        ok: false, 
        error: 'User not found'
      });
    }
    res.json({ 
      ok: true, 
      data: user.toJSON()
    });
  } catch (err) {
    console.error('获取用户详情错误:', err);
    res.status(500).json({ 
      ok: false, 
      error: err.message,
      detail: '请检查数据库连接和表结构'
    });
  }
});

// 调试路由：用于课堂上的冒烟测试
router.get('/debug/users', async (req, res) => {
  try {
    const users = await User.findAll({
      limit: 10,
      order: [['id', 'ASC']]
    });
    
    res.json({ 
      ok: true, 
      data: users.map(user => user.toJSON()),
      metadata: {
        count: users.length,
        timestamp: new Date().toISOString(),
        author: require('../package.json').author,
        version: require('../package.json').version
      }
    });
  } catch (err) {
    console.error('调试路由错误:', err);
    res.status(500).json({ 
      ok: false, 
      error: err.message,
      detail: '请检查数据库连接和表结构'
    });
  }
});

module.exports = router;